/*
 * elementLoader.l
 *
 *  Created on: Apr 21, 2011
 *      Author: mariano
 */

%{
#include "../include/element.h"
#include "../include/array.h"
	
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static Array * elements = NULL;

char * reduceElement(char * src, int srcSize) {
	int i;
	char * out = malloc(sizeof(char) * srcSize);
	int outSize=0;

	// Get rid of duplicated spaces
	for(i=0;i<srcSize && src[i] != '\0';i++)
		if(src[i] != '+' && (src[i] != ' ' || (i > 0 && src[i] == ' ' && src[i-1] != ' ')))
				out[outSize++] = src[i]; // Replace \n for spaces			
	
	// Erase last possible space
	if(out[outSize-1] == ' ')
		out[outSize-1] = '\0';
	else out[outSize++] = '\0';
	
	// Resize it and return
	out = realloc(out, outSize);
	return out;
}
	
%}

%option noyywrap

element [A-Za-z0-9!\t]+[" "]*

%%

[" "]*{element}+/[\n]? { 
	yytext[yyleng] = '\0';

	char * tmp = reduceElement(yytext,yyleng+1);
	Element * e = newElement(tmp);
	add(elements,e);
	free(tmp);
}

. {}
\n {}

%%




Array * loadElements(char * filename){
	elements = newArray();
	FILE * tmp = yyin;
	yyin = fopen(filename == NULL ? "myelements.name" : filename, "r");
	if(yyin==NULL){
	  return NULL;
	}
	
	loaderlex();
	yyin = tmp;
	
	Array * out = copyArray(elements);
	deleteArray(elements);
	return out;
}